package com.example.trb.component;

import com.example.trb.util.result.CommonResult;
import com.example.trb.util.result.ReturnCode;
import com.example.trb.util.result.UserReturnCode;
import com.fasterxml.jackson.core.JsonEncoding;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@Component
public class SecurityInterceptor implements HandlerInterceptor {
    @Value("${session_user}")
    String userKey;
    @Autowired
    ObjectMapper objectMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        HttpSession session = request.getSession();
        Object attribute = session.getAttribute(userKey);

        if (attribute != null) {
            return true;
        } else {
            writeResponse(response, UserReturnCode.LOGIN_FIRST);
        }
        return false;
    }

    public void writeResponse(HttpServletResponse response, ReturnCode returnCode) throws IOException {
        ServletOutputStream os = response.getOutputStream();
        String result = objectMapper.writeValueAsString(
                CommonResult.fail(returnCode.code(), returnCode.message())
        );
        os.print(new String(result.getBytes(), "ISO8859-1"));
        os.close();
    }
}
